package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import jsyf.oa.dao.device.DeviceTransportCompanyDao;
import jsyf.oa.dao.system.*;
import jsyf.oa.entity.device.DeviceTransportCompanyEntity;
import jsyf.oa.entity.system.Company2bankEntity;
import net.sf.json.JSONArray;
import com.alibaba.fastjson.JSONObject;

import jsyf.com.constant.Const;
import jsyf.com.util.BaseUtils;
import jsyf.com.util.FastJsonConvert;

import jsyf.oa.entity.system.Company2BrandEntity;
import jsyf.oa.entity.system.CompanyEntity;
import jsyf.oa.entity.system.CompanyStockEntity;
import jsyf.oa.facade.system.CompanyFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class CompanyService implements CompanyFacade {

    //公司dao
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private DepartDao departDao;
    @Autowired
    private Company2BrandDao company2BrandDao;
    @Autowired
    private CompanyStockDao companyStockDao;
    @Autowired
    private DeviceTransportCompanyDao deviceTransportCompanyDao;
    @Autowired
    private Company2bankDao company2bankDao;
    @Autowired
    private UserDao userDao;

    @Override
    public String save(String jsonData) {
        CompanyEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), CompanyEntity.class);
        Integer rows;
        if ("0".equals(entity.getId()) || StringUtils.isBlank(entity.getId())) {
            rows = companyDao.add(entity);
        } else {
            CompanyEntity companyEntity = companyDao.getById(entity.getId());
            companyEntity.setName(entity.getName());
            companyEntity.setParentId(entity.getParentId());
            companyEntity.setUpdateUserId(entity.getUpdateUserId());
            rows = companyDao.update(companyEntity);
        }
        return rows == 0 ? "" : entity.getId();
    }

    @Override
    public JSONObject add(String jsonData) {
        JSONObject jsonObject = JSON.toJavaObject(JSON.parseObject(jsonData), JSONObject.class);
        JSONObject jsonObjectCompany = jsonObject.getJSONObject("company");
        String jsonObjectStockList = jsonObject.getString("stockList");
        String parentId = jsonObjectCompany.getString("parentId");
        CompanyEntity companyEntity = JSON.toJavaObject(jsonObjectCompany, CompanyEntity.class);
        companyEntity.setDelFlag(0);
        companyEntity.setSortNo(0);
        if (!StringUtils.isBlank(parentId)) {
            companyEntity.setParentId(parentId);
        } else {
            companyEntity.setParentId("0");
        }

        JSONObject result = new JSONObject();
        result.put("addNewId", companyDao.add(companyEntity));
        List<CompanyStockEntity> entity = (List<CompanyStockEntity>) JSONArray.toCollection(JSONArray.fromObject(jsonObjectStockList), CompanyStockEntity.class);

        for (int i = 0; i < entity.size(); i++) {
            CompanyStockEntity model = entity.get(i);
            model.setCompanyId(companyEntity.getId());
            if (model.getStockArea().equals("直发客户交机")) {
                model.setSortNo(1);
            } else {
                model.setSortNo(0);
            }
            companyStockDao.add(model);
        }
        return result;
    }


    @Override
    public Boolean updateDevice(String jsonData) {
        JSONObject jsonObject = JSON.toJavaObject(JSON.parseObject(jsonData), JSONObject.class);
        String parentId = jsonObject.getString("parentId");
        String companyId = jsonObject.getString("id");
        CompanyEntity companyEntity = JSON.toJavaObject(JSON.parseObject(jsonData), CompanyEntity.class);
        if (jsonObject.containsKey("deviceId")) {
            String deviceId = jsonObject.getString("deviceId");
            String[] result1 = deviceId.split(",");
            company2BrandDao.removeByCondition(" and COMPANY_ID=?", new String[]{companyId});
            for (int i = 0; i < result1.length; i++) {
                JSONObject jsonObjectBrand = new JSONObject();
                jsonObjectBrand.put("companyId", companyId);
                jsonObjectBrand.put("brandId", result1[i]);
                Company2BrandEntity company2BrandEntity = JSON.toJavaObject(jsonObjectBrand, Company2BrandEntity.class);
                company2BrandDao.add(company2BrandEntity);
            }


        }
        if (!StringUtils.isBlank(parentId)) {
            companyEntity.setParentId(parentId);
        } else {
            companyEntity.setParentId("0");
        }
        CompanyEntity oldCompany = companyDao.getById(companyId);
        companyEntity.setCreateUserId(oldCompany.getCreateUserId());
        companyEntity.setDelFlag(oldCompany.getDelFlag());
        companyEntity.setCreateTime(oldCompany.getCreateTime());
        companyEntity.setSortNo(oldCompany.getSortNo());
        return companyDao.update(companyEntity) > 0;
    }

    @Override
    public Boolean update(String jsonData) {
        JSONObject jsonObject = JSON.toJavaObject(JSON.parseObject(jsonData), JSONObject.class);
        JSONObject jsonObjectCompany = jsonObject.getJSONObject("company");
        String jsonObjectStockList = jsonObject.getString("stockList");
        String transportList = jsonObject.getString("transportList");
        String bankList = jsonObject.getString("bankList");
        String parentId = jsonObjectCompany.getString("parentId");
        String companyId = jsonObjectCompany.getString("id");
        CompanyEntity companyEntity = JSON.toJavaObject(jsonObjectCompany, CompanyEntity.class);
        if (jsonObjectCompany.containsKey("deviceId")) {
            //设备配置
            String deviceId = jsonObjectCompany.getString("deviceId");
            String[] result1 = deviceId.split(",");
            company2BrandDao.removeByCondition(" and COMPANY_ID=?", new String[]{companyId});
            for (int i = 0; i < result1.length; i++) {
                JSONObject jsonObjectBrand = new JSONObject();
                jsonObjectBrand.put("companyId", companyId);
                jsonObjectBrand.put("brandId", result1[i]);
                Company2BrandEntity company2BrandEntity = JSON.toJavaObject(jsonObjectBrand, Company2BrandEntity.class);
                company2BrandDao.add(company2BrandEntity);
            }
        } else {
            //公司库存地配置
            companyStockDao.removeByCondition(" and COMPANY_ID=?", new String[]{companyId});
            List<CompanyStockEntity> entity = (List<CompanyStockEntity>) JSONArray.toCollection(JSONArray.fromObject(jsonObjectStockList), CompanyStockEntity.class);
            for (int i = 0; i < entity.size(); i++) {
                CompanyStockEntity model = entity.get(i);
                model.setCompanyId(companyEntity.getId());
                if (model.getStockArea().equals("直发客户交机")) {
                    model.setSortNo(1);
                } else {
                    model.setSortNo(0);
                }
                companyStockDao.add(model);
            }
            //运输公司配置
            deviceTransportCompanyDao.removeByCondition(" and COMPANY_ID=?", new String[]{companyId});
            List<DeviceTransportCompanyEntity> deviceTransport = (List<DeviceTransportCompanyEntity>) JSONArray.toCollection(JSONArray.fromObject(transportList), DeviceTransportCompanyEntity.class);

            for (int i = 0; i < deviceTransport.size(); i++) {
                DeviceTransportCompanyEntity model = deviceTransport.get(i);
                model.setCompanyId(companyEntity.getId());
                deviceTransportCompanyDao.add(model);
            }
            //公司开户行配置
            company2bankDao.removeByCondition(" and COMPANY_ID=?", new String[]{companyId});
            List<Company2bankEntity> company2bankEntity = (List<Company2bankEntity>) JSONArray.toCollection(JSONArray.fromObject(bankList), Company2bankEntity.class);
            for (int i = 0; i < company2bankEntity.size(); i++) {
                Company2bankEntity model = company2bankEntity.get(i);
                model.setCompanyId(companyEntity.getId());
                model.setSortNo(i);
                company2bankDao.add(model);
            }
        }
        if (!StringUtils.isBlank(parentId)) {
            companyEntity.setParentId(parentId);
        } else {
            companyEntity.setParentId("0");
        }
        CompanyEntity oldCompany = companyDao.getById(companyId);
        companyEntity.setCreateUserId(oldCompany.getCreateUserId());
        companyEntity.setDelFlag(oldCompany.getDelFlag());
        companyEntity.setAvailableBrands(oldCompany.getAvailableBrands());
        companyEntity.setCreateTime(oldCompany.getCreateTime());
        companyEntity.setSortNo(oldCompany.getSortNo());
        return companyDao.update(companyEntity) > 0;
    }

    @Override
    public Boolean deleteById(String jsonData) {
        return companyDao.delById(JSON.parseObject(jsonData).getString("id")) > 0;
    }

    @Override
    public Boolean removeById(String jsonData) {
        return companyDao.removeById(JSON.parseObject(jsonData).getString("id")) > 0;
    }


    @Override
    public String delById(String id) {
        Integer departCount = departDao.getPageCount(" AND COMPANY_ID=? AND DEL_FLAG=0", new Object[]{id});
        if (departCount > 0) {
            return BaseUtils.errorrRespond("删除失败，请先删除部门");
        }
        int flag = this.companyDao.delById(id);
        if (Const.INT_ONE == flag) {
            return BaseUtils.succsessObjRespond("删除成功");
        }
        return BaseUtils.errorrRespond("删除失败");
    }

    @Override
    public List<JSONObject> getCompanyList() {
        List<JSONObject> jsonObjectList = this.companyDao.getJSONListByCondition(" AND DEL_FLAG=0", null);
        return jsonObjectList;
    }


    @Override
    public JSONObject getCompanyListByPage(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject result = new JSONObject();
        JSONObject objSendData = new JSONObject();
        String requestPage;
        String pageSize;
        if (jsonParams.containsKey("requestPage") && jsonParams.containsKey("pageSize")) {
            requestPage = jsonParams.getString("requestPage");
            pageSize = jsonParams.getString("pageSize");
        } else {
            requestPage = "1";
            pageSize = Integer.MAX_VALUE + "";
        }
        StringBuffer sbCondition = new StringBuffer();
        sbCondition.append(" AND DEL_FLAG=0 AND PARENT_ID='201712161613432EAF27DBCCB7D0E6CA'");
        String companyNameKey = jsonParams.getString("companyNameKey");
        if (!StringUtils.isBlank(companyNameKey)) {
            sbCondition.append(" AND (All_NAME like '%" + companyNameKey + "%' OR NAME like '%" + companyNameKey + "%')");
        }
        sbCondition.append(" ORDER BY SORT_NO");
        List<JSONObject> records = companyDao.getJSONListByPage(sbCondition.toString(), new Object[]{},
                Integer.parseInt(requestPage), Integer.parseInt(pageSize));
        int recordCount = companyDao.getPageCount(sbCondition.toString(), new Object[]{});
        int recordSize = Integer.valueOf(pageSize).intValue();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % recordSize == 0 ? recordCount / recordSize : (recordCount / recordSize) + 1;
        //子对象
        objSendData.put("recordCount", recordCount);
        objSendData.put("pageCount", pageCount);
        objSendData.put("requestPage", 1);
        result.put("pager", objSendData);
        // 子数组对象
        result.put("records", records);
        return result;

    }

    @Override
    public JSONObject getCompanyById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject parentCompany = companyDao.getCompanyParent(jsonParams.getString("id"));
        List<JSONObject> stock = companyStockDao.getJSONListByCondition(" and COMPANY_ID=? ORDER BY SORT_NO", new Object[]{jsonParams.getString("id")});
        List<JSONObject> transportList = deviceTransportCompanyDao.getJSONListByCondition(" and COMPANY_ID=? ", new Object[]{jsonParams.getString("id")});
        List<JSONObject> bankList = company2bankDao.getJSONListByCondition(" and COMPANY_ID=? ORDER BY SORT_NO", new Object[]{jsonParams.getString("id")});
        JSONObject company = companyDao.getJSONById(jsonParams.getString("id"));
        if (parentCompany != null) {
            company.put("parentCompanyName", parentCompany.getString("name"));
        }
        JSONObject companyInfo = new JSONObject();
        companyInfo.put("company", company);
        companyInfo.put("stock", stock);
        companyInfo.put("transportList", transportList);
        companyInfo.put("bankList", bankList);
        return companyInfo;
    }

    @Override
    public Boolean sort(String companyIds) {
        return companyDao.sort(companyIds);
    }

    @Override
    public List<JSONObject> getCompanyListByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and main=1 and id=?", new Object[]{userId});
        String manageFlag = userList.get(0).getString("manageFlag");
        List<JSONObject> companyList = new ArrayList<JSONObject>();
        if (!StringUtils.isBlank(manageFlag)) {
            if (!manageFlag.equals("1")) {
                companyList = companyDao.getJSONListByCondition(" and id in (SELECT \n" +
                        "v_sys_part_time_for_report.companyId\n" +
                        "FROM v_sys_part_time_for_report\n" +
                        "WHERE userId=?)\n" +
                        "and t_sys_company.del_flag=0 AND (t_sys_company.PARENT_ID='201712161613432EAF27DBCCB7D0E6CA')\n" +
                        "group by t_sys_company.id \n" +
                        "order by t_sys_company.sort_no", new Object[]{userId});
            } else {
                companyList = companyDao.getJSONListByCondition(" and del_flag=0 and PARENT_ID='201712161613432EAF27DBCCB7D0E6CA' group by t_sys_company.id order by t_sys_company.sort_no", new Object[]{});
            }
        }
        return companyList;

    }

    @Override
    public List<JSONObject> getCompanyByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and main=1 and id=?", new Object[]{userId});
        String manageFlag = userList.get(0).getString("manageFlag");
        List<JSONObject> companyList = new ArrayList<JSONObject>();
        if (!StringUtils.isBlank(manageFlag)) {
            if (manageFlag.equals("1")) {
                companyList = companyDao.getJSONListByCondition("and id in (SELECT \n" +
                        "                        v_sys_part_time_for_report.companyId\n" +
                        "                        FROM v_sys_part_time_for_report\n" +
                        "                        WHERE userId='" + userId + "') OR PARENT_ID in (SELECT \n" +
                        "                        v_sys_part_time_for_report.companyId\n" +
                        "                        FROM v_sys_part_time_for_report\n" +
                        "                        WHERE userId='" + userId + "')\n" +
                        "AND DEL_FLAG=0 ORDER BY SORT_NO", new Object[]{});
            } else {
                companyList = companyDao.getJSONListByCondition(" and id in (SELECT \n" +
                        "                        v_sys_part_time_for_report.companyId\n" +
                        "                        FROM v_sys_part_time_for_report\n" +
                        "                        WHERE userId='" + userId + "') \n" +
                        "AND DEL_FLAG=0 ORDER BY SORT_NO ", new Object[]{});
            }
        }
        return companyList;

    }

    @Override
    public JSONObject getContactAndTelByAddress(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String storeAddress = jsonParams.getString("storeAddress");
        JSONObject stock = companyStockDao.getContactAndTelByAddress(" and STOCK_AREA=? ", new Object[]{storeAddress});
        return stock;
    }

    @Override
    public List<JSONObject> getBanksByCompanyId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyId = jsonParams.getString("companyId");
        return company2bankDao.getBanksByCompanyId(companyId);
    }

    @Override
    public JSONObject getBanksByCompanyId2BankId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String id = jsonParams.getString("id");
        Company2bankEntity company2bankEntity = (Company2bankEntity) company2bankDao.getIBaseEntityById(id);
        return (JSONObject) JSON.toJSON(company2bankEntity);
    }
}
